﻿using MediatR;
using S.Archives.Api.Application.Command;
using S.Archives.Domain.S.ArchivesModel;
using S.Archives.Infrstructre.Imp;
using S.Archives.Infrstructre.InterFace;
using S.Common.helper;
using System.Linq;

namespace S.Archives.Api.Application.CommandHandlers
{
    public class SheepFilePLDeleteCommandHandler : IRequestHandler<SheepFilePLDeleteCommand, string>
    {
         private readonly ISheepFileRepository sheepFileRepository;
         //获取Apollo配置
         private readonly IConfiguration configuration;
        //获取Token令牌
         private readonly IHttpContextAccessor httpContextAccessor;
        public SheepFilePLDeleteCommandHandler(ISheepFileRepository shepFileRepository, IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            this.sheepFileRepository = shepFileRepository;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 批量删除羊只档案
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<string> Handle(SheepFilePLDeleteCommand request, CancellationToken cancellationToken)
        {
            var ids= request.Id.Split(',');

            List<SheepFileModel> Model = new List<SheepFileModel>();

            var Gateway = configuration.GetValue<string>("Gateway");

            //先判断是否都为空档案
            foreach (var item in ids)
            {
                int id = Convert.ToInt32(item);
                var sheepmodel= sheepFileRepository.GetAll().FirstOrDefault(x=>x.SheepFileId==id);
                if (sheepmodel == null)
                {
                    return "flase";
                }
                if (sheepmodel.PresenceState > 1 || sheepmodel.WanderReproductiveState > 0)
                {
                    return  sheepmodel.EarTag;
                }
                else
                {
                    //修改耳标状态为未使用
                    HttpClientHelper.PostResponse(Gateway + $"/ggyset/api/EarTag/UpdMarkStateTwo?EarTag={sheepmodel.EarTag}", "");
                    Model.Add(sheepmodel);
                    
                }

            }
            var data = await sheepFileRepository.RemoveRangeAsync(Model);
            if (data)
            {
                return "true";
            }
            else
            {
                return "flase";
            }



        }
    }
}
